package com.team24.hotel.controller;


import com.team24.hotel.domain.User;
import com.team24.hotel.service.IMailService;
import com.team24.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/register")
public class RegisterController {
    @Autowired
    private UserService userService;
    @Autowired
    private IMailService iMailService;

    private String validateCheckCode = null;

    @RequestMapping(value = "/register1")
    public String registsave(Model model) {
        model.addAttribute("user",new User());
        return "register";
    }

    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    @ResponseBody
    public String addData( User user,Model model,String stringUserBirthday)  {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date date=null;
        try {
            date=simpleDateFormat.parse(stringUserBirthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUserBirthday(date);
        int a = userService.saveUser(user);
        if(a>0) {
            return "ok";
        }
        else {
            return "error";
        }
    }

    @RequestMapping("getCheckCode")
    @ResponseBody
    public String getCheckCode(String email) {
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        String message = "您的验证码：" + checkCode;
        System.out.println(checkCode);
        validateCheckCode = checkCode;
        try {
            System.out.println("------------" + checkCode);
            iMailService.sendSimpleMail(email, "注册验证码", message);
        } catch (Exception e) {
            return "";
        }
        return checkCode;
    }
}
